import 'dart:ui' as ui;

import 'package:flutter/material.dart';

class KqPadSliderComponentShape extends SliderComponentShape {
  final Size size;
  final double sliderWidth;
  final ui.Image? image;

  const KqPadSliderComponentShape(
      {required this.image, required this.sliderWidth, Size? size})
      : size = size ?? const Size(28, 28);

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return size;
  }

  @override
  void paint(PaintingContext context, Offset center,
      {required Animation<double> activationAnimation,
      required Animation<double> enableAnimation,
      required bool isDiscrete,
      required TextPainter labelPainter,
      required RenderBox parentBox,
      required SliderThemeData sliderTheme,
      required TextDirection textDirection,
      required double value,
      required double textScaleFactor,
      required Size sizeWithOverflow}) {
    double dx = size.width / 2.0;
    double dy = size.height / 2.0;

    if (image != null) {
      final Rect sourceRect =
          Rect.fromLTWH(0, 0, image!.width.toDouble(), image!.width.toDouble());

      double left = center.dx - dx;
      double top = center.dy - dy;
      double right = center.dx + dx;
      double bottom = center.dy + dy;
      Rect destinationRect = Rect.fromLTRB(
          (center.dx - dx / 4) < 0
              ? center.dx - dx + dx / 2
              : center.dx >= sliderWidth
                  ? left - dx / 2
                  : left,
          top,
          (center.dx - dx / 4) < 0
              ? center.dx + dx + dx / 2
              : center.dx >= sliderWidth
                  ? right - dx / 2
                  : right,
          bottom);

      final Canvas canvas = context.canvas;
      final Paint paint = Paint();
      paint.isAntiAlias = true;

      // 绘制滑块
      canvas.drawImageRect(image!, sourceRect, destinationRect, paint);
    }
  }
}
